/*
 * Copyright 2010-2011 CGT&DC ISA RAS
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package websolve.workflow.fileupload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    private String uploadDir;

    public void init(ServletConfig config) throws ServletException {
        uploadDir = (String) config.getServletContext().getAttribute("upload-dir");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        HttpSession session = null;
        UploadListener listener = null;
        long contentLength = 0;

        if (((session = request.getSession()) == null)
                || ((listener = (UploadListener) session.getAttribute("LISTENER")) == null)
                || ((contentLength = listener.getContentLength()) < 1)) {
            out.write(" ");
            out.close();
            return;
        }

        response.setContentType("text/html");
        long percentComplite = ((100 * listener.getBytesRead()) / contentLength);
        out.print(percentComplite);
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        System.out.println("File uploader invoked!");
        response.setContentType("text/html");

        // create file upload factory and upload servlet
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // set file upload progress listener
        UploadListener listener = new UploadListener();
        HttpSession session = request.getSession();
        session.setAttribute("LISTENER", listener);
        // upload servlet allows to set upload listener
        upload.setProgressListener(listener);

        List items = null;
        FileItem fileItem = null;
        String filename = null;
        try {
            // iterate over all uploaded files
            items = upload.parseRequest(request);
            for (Iterator i = items.iterator(); i.hasNext();) {
                fileItem = (FileItem) i.next();
                if (!fileItem.isFormField()) {
                    if (fileItem.getSize() > 0) {
                        String fileName = UUID.randomUUID().toString();
                        int dotPos = fileItem.getName().indexOf(".");
                        if (dotPos > 0) {
                            fileName += fileItem.getName().substring(dotPos);
                        }
                        fileItem.write(new File(uploadDir + "/" + fileName));
                        fileItem.delete();
                        response.getWriter().write(fileName);
                    }
                }
            }
            // indicate that the upload was successfull
            // response.getWriter().write("upload successful");
        } catch (FileUploadException e) {
            response.getWriter().write(e.getMessage());
        } catch (Exception e) {
            response.getWriter().write(e.getMessage());
        } finally {
            session.removeAttribute("LISTENER");
        }
    }

}
